%% 追赶法例子
%a = [2 1 1 1 1];
%b = [0 -1 -1 -1 -1];
%c = [2 2 2 2 0];
%B = [6 7 9 11 1];

% a=full(diag(A3, 0))';
% b=[0,full(diag(A3, 1))'];
% c = [full(diag(A3, -1))', 0];
% B = rand(4096,1);
% n_vec=length(a);
% N=n_vec;
% x = tridiagSolver(a,b,c,B,n_vec);
% A = spdiags([c(:) b(:) a(:)], [-1 0 1], N, N); 
% y = A * x';
%A = diag(a)+diag(repmat([-1],1,4), -1)+ diag(repmat([2],1,4),1);
%C=A*x';
load('A3.mat');
a=full(diag(A3, 0))';
b=[0,full(diag(A3, 1))'];
c = [full(diag(A3, -1))', 0];
B = rand(4096,1);
n_vec=length(a);
N=n_vec;
x_trisv = tridiagSolver(a,b,c,B,N);
b1 = circshift(b, -1);
c1 = circshift(c, 1);
A = spdiags([b1(:) a(:) c1(:)], [-1 0 1], N, N); 
A=full(A);
C=A*x_trisv';
x_msv=A\B;

%% 追赶法解三对角线性方程组 
% 输入主对角元素向量，下次对角元素向量，上次对角元素向量，方程右边的向量，阶数
function x = tridiagSolver(a,b,c,B,n)
    q(1) = a(1);
    for i = 2:n
        p(i) = b(i)/q(i-1);
        q(i) = a(i)-p(i)*c(i-1);
    end
    y(1) = B(1);
    for i = 2:n
        y(i) = B(i)-p(i)*y(i-1);
    end
    x(n) = y(n)/q(n);
    for i = n-1:-1:1
        x(i)=(y(i)-c(i)*x(i+1))/q(i);
    end
end
